package cn.witsky.rtp2ws.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.witsky.rtp2ws.Server;
import io.netty.util.internal.StringUtil;

public class HttpDownLoad {
	private static Logger logger = LoggerFactory.getLogger(HttpDownLoad.class);
	public static final int cache = 10 * 1024;

	

	/**
	 * 根据url下载文件，保存到filepath中
	 * 
	 * @param url
	 * @param filepath
	 * @return
	 */
	public static String download(String callId, String url) {
		String fileName = "";
		InputStream inputStream = null;
		FileOutputStream fileOutputStream = null;
		try {
			HttpClient client = new DefaultHttpClient();

			client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,5000);
			client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,5000);
//			RequestConfig requestConfig =  RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000).build();
			HttpGet httpget = new HttpGet(url);
//			httpget.setConfig(requestConfig);
			HttpResponse response = client.execute(httpget);
			if(response.getStatusLine().getStatusCode()!=200) {
				logger.warn("下载会话 callId：{}的录音文件失败",callId);
				return "";
			}
			HttpEntity entity = response.getEntity();
			fileName = getFileName(response);
			if (StringUtil.isNullOrEmpty(fileName)) {
				int len = url.split("/").length;
				fileName = url.split("/")[len - 1];
			}
			if (fileName == null || fileName.equals("")) {
				return "";
			}
			fileName= callId + "." + FileUtil.getFileExtension(fileName);
			String filePath = Server.downLoadDir+"/" +fileName;
			logger.debug("下载会话 callId：{} 文件地址:{}",callId,filePath);
			inputStream = entity.getContent();
			File file = new File(filePath);
			file.getParentFile().mkdirs();
			fileOutputStream = new FileOutputStream(file);
			/**
			 * 根据实际运行效果 设置缓冲区大小
			 */
			byte[] buffer = new byte[cache];
			int ch = 0;
			while ((ch = inputStream.read(buffer)) != -1) {
				fileOutputStream.write(buffer, 0, ch);
			}
			fileOutputStream.flush();
			return fileName;
		} catch (Exception e) {
			logger.error("下载会话 callId："+callId+"的录音文件出现异常:",e);
			return "";
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if (fileOutputStream != null) {
				try {
					fileOutputStream.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 获取response header中Content-Disposition中的filename值
	 * 
	 * @param response
	 * @return
	 */
	public static String getFileName(HttpResponse response) {
		Header contentHeader = response.getFirstHeader("Content-Disposition");
		String filename = null;
		if (contentHeader != null) {
			HeaderElement[] values = contentHeader.getElements();
			if (values.length == 1) {
				NameValuePair param = values[0].getParameterByName("filename");
				if (param != null) {
					try {
						// filename = new String(param.getValue().toString().getBytes(), "utf-8");
						// filename=URLDecoder.decode(param.getValue(),"utf-8");
						filename = param.getValue();
					} catch (Exception e) {
						logger.error("获取fileName出现异常:",e);
					}
				}
			}
		}
		return filename;
	}

	public static void main(String[] args) {
		String url = "https://www.baidu.com/img/flexible/logo/pc/result.png";
		HttpDownLoad.download("test001", url);
	}
}
